﻿/**
 * Jean-François Desgagné 2009 Portfolio
 * Copyright (c) 2009 Jean-François Desgagné <jfesgagne@gmail.com>
 * 
 * This work is licensed under a Creative Commons Attribution 3.0 United States License.
 * Some Rights Reserved.
 */
package com.jfdesgagne.jfdesgagne09.shell.model {
    import com.jfdesgagne.jfdesgagne09.shell.ApplicationFacade;
	import com.jfdesgagne.utils.XMLFileParser;
    
    import flash.events.Event;
	import flash.events.IOErrorEvent;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
	import flash.xml.XMLDocument;
	
	import flash.display.Stage;
	import flash.display.LoaderInfo;
    
    import org.puremvc.as3.multicore.interfaces.IProxy;
    import org.puremvc.as3.multicore.patterns.proxy.Proxy;

    public class ConfigProxy extends Proxy implements IProxy {
        public static const NAME:String = "ConfigProxy";
        public var parameters:Object;
		private var _urlLoader:URLLoader;
		private var _urlRequest:URLRequest;
		protected var _config:Object;
		
        public function ConfigProxy(stage:Object) {
        	super(NAME, new Object());
			
			this.parameters = LoaderInfo(stage.loaderInfo).parameters;
		
			if (this.parameters == null) this.parameters = new Object();
			if (this.parameters.http_address == null) this.parameters.http_address = "http://localhost/jfdesgagne.com/";
			
			this._urlRequest = new URLRequest(this.parameters.http_address+"system/config/config.xml")
			this._urlLoader = new URLLoader(this._urlRequest);
			this._urlLoader.addEventListener(Event.COMPLETE, this._configLoadCompletedHandler);
			this._urlLoader.addEventListener(IOErrorEvent.IO_ERROR, this._configErrorHandler);
			
        }
		
		public static function getInstance():ConfigProxy {
			return ApplicationFacade.getInstance(ApplicationFacade.NAME).retrieveProxy( ConfigProxy.NAME ) as ConfigProxy;
		}
		
		private function _configErrorHandler($event:IOErrorEvent):void {
			this._urlLoader.load(this._urlRequest);
		}
		
		private function _configLoadCompletedHandler(event:Event):void {
			this._config = new Object();
			var xml:XMLDocument = new XMLDocument(event.target.data);
			var xmlFileParser:XMLFileParser = new XMLFileParser();
				xmlFileParser.parseXML(xml, this._config);
			this.sendNotification(ApplicationFacade.CONFIGPROXY_LOADED);
		}
		
		public function get config():Object {
			return this._config.configuration_file.configuration
		}
    }
}